package gui;
import java.util.Arrays;
import java.util.Comparator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

/**
 * class SortListener.
 * sorts the table in ascending / descending order by column (user's choice).
 * @author michal
 *
 */
public class SortListener implements Listener{
	Table table;	//info table

	/**
	 * c-tor gets a table
	 * @param table
	 */
	public SortListener(Table table) {
		super();
		this.table = table;
	}

	/**
	 * sorts the table
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void handleEvent(Event e) {
		// determine new sort column and direction
		TableColumn sortColumn = table.getSortColumn();
		TableColumn currentColumn = (TableColumn) e.widget;
		int dir = table.getSortDirection();
		if (sortColumn == currentColumn) {
			dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
		} else {
			table.setSortColumn(currentColumn);
			dir = SWT.UP;
		}
		// sort the data based on column and direction
		//  final int index = currentColumn == column1 ? 0 : 1;
		int indexCheck = 0 ;
		int i;
		for ( i=0;i<table.getColumnCount();i++){
			if (table.getColumn(i)==currentColumn)
				indexCheck = i;
		}
		final int index = indexCheck;
		final int direction = dir;
		final String[][] data = new String[table.getItemCount()][];
		for ( i=0;i<table.getItemCount();i++){
			data[i] = new String[table.getColumnCount()];
			for (int j=0;j<table.getColumnCount();j++){

				data[i][j]=table.getItem(i).getText(j);
			}
		}
		//sorting the data
		Arrays.sort(data, new Comparator() {
			public int compare(Object arg0, Object arg1) {
				String[] a = (String[]) arg0;
				String[] b = (String[]) arg1;	
				
				if (a[index].equals(b[index]))
					return 0;
				if (direction == SWT.UP) { //ascending order
					if (a[index].compareTo(b[index])<0)
						return -1;
					else
						return 1;
				}
				if (a[index].compareTo(b[index])<0)	//descending order
					return 1;
				else
					return -1;
			}
		});
		// update data displayed in table
		table.setSortDirection(dir);
		table.clearAll();
		TableItem item;
		for (i=0;i<data.length;i++){
			item = table.getItem(i);
			for (int j=0;j<data[i].length;j++){
				item.setText(j,data[i][j]);

			}
		}
		table.addListener(SWT.SetData, new Listener() {
			public void handleEvent(Event e) {
				TableItem item = (TableItem) e.item;				
				int index = table.indexOf(item);
				
				if (data.length>index){
					System.out.println(data.length);
					String[] datum = data[index];				
					for (int i=0;i<table.getColumnCount();i++){
						item.setText(i,datum[i]);
					}
				}
			}
		});
	}

}




